// pages/assess/index/index.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.command

Page({

    /**
     * 页面的初始数据
     */
    data: {
        sequence:[
            {title:"畜牧保小程序使用说明"},
            {title:"农业养殖保险"},
            {title:"英德市拨付政策性农业公示"},
            {title:"牲畜保险存在问题与建议"},
            {title:"金额估算模型"}
        ]
    },
    touchmove(){},
    addPic1: function (e) {
        var that = this;
        var n = 1;
        wx.chooseImage({
          count: n, // 默认9，设置图片张数
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            // console.log(res.tempFilePaths)
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            var tempFilePaths = res.tempFilePaths
            wx.getFileSystemManager().readFile({
                filePath: tempFilePaths[0],
                encoding: 'base64',
                success: function (res) {
                    //调用方法
                    that.setData({
                        imgBase64: res.data
                    })
                    // that.getImgInfo(res.data)
                },fail(){
                    console.log("zxc")
                },
            })
            that.setData({
                filePath: tempFilePaths,
                addOk: true
            });
          }
        })
      },

      toNext(){
        
        let that = this
        let desc = this.data.desc
        if (!that.data.addOk) {
          wx.showToast({
            icon: "none",
            title: '请选择图片'
          })
          return
        }
        wx.showLoading({
          title: '发布中...',
        })
        let promiseArr = [];
        promiseArr.push(new Promise((reslove, reject) => {
            let item = that.data.filePath[0];
            console.log(item)
            let suffix = /\.\w+$/.exec(item)[0]; //正则表达式返回文件的扩展名
            wx.cloud.uploadFile({
                cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
                filePath: item, // 小程序临时文件路径
            }).then(res => {
            console.log("上传结果", res.fileID)
            this.setData({
                fileIDs: res.fileID
            })
            app.globalData.anmimgPath = res.fileID
            reslove()
                that.toinfomation()
            }).catch(error=>{
            console.log("上传失败",error);
            })
        }))
      },
    
      toinfomation() {
        let that = this
        that.getBaiduToken().then(res => {
            //获取token
            const token = res.data.access_token
            console.log(token)
            wx.request({
              url: "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal",
              header: {
                "Content-type": "application/x-www-form-urlencoded",//决定用哪种post请求，是固定的
              },
              method: 'post',   //请求固定为post请求
                  data: {           //请求时需要上传的数据
                    image: that.data.imgBase64,	//图片编码数据
                    access_token: token,//获取的token权限
                    // baike_num: 1	//想得到的百度百科数量
                  },
              success: function (res, resolve) {
                console.log(res)
                //将 res.data.words_result数组中的内容加入到words中           
                that.setData({
                  words: res.data.result[0].name
                })
                console.log(res.data)
                if(res.data.result[0].name == "非动物"){
                    wx.hideLoading({
                      success: (res) => {wx.showToast({
                        title: '非动物',
                        icon:"none"
                      })},
                    })
                    return
                }
                app.globalData.anm_name = res.data.result[0].name
                app.globalData.a1 = res.data.result[0].name
                app.globalData.a2 = res.data.result[1].name
                app.globalData.a3 = res.data.result[2].name
                app.globalData.a4 = res.data.result[3].name
                console.log(app.globalData.anm_name)
                console.log('识别后： ' + res.data.result[0].name)
                
                wx.cloud.database().collection('anmnum').doc("b69f67c06291c7c104e797246ca43290").get({
                    success: res => {
                        that.setData({
                            anm_num: res.data.num
                        })
                        let num1 = res.data.num + 1
                        let flag = 8300910000+num1
                        let num2 = "XJ"+flag
                        wx.cloud.database().collection('anminfo').add({
                            data:{
                                name: that.data.words,
                                num: num2
                            },
                            success: res=>{
                                app.globalData.anum = num2
                                wx.cloud.database().collection('anmnum').doc("b69f67c06291c7c104e797246ca43290").update({
                                    data:{
                                        num: num1
                                    },
                                    success: resp=>{            
                                        if(that.data.selectF){ 
                                            wx.navigateTo({
                                            url: '../infomation/index',
                                          })  }else{   
                                            wx.navigateTo({
                                            url: '../../identify/information/index',
                                          })}
                                        
                                          wx.hideLoading()
                                          wx.showToast({
                                            title: '发布成功',
                                          })
                                    }
                                })
                            }
                        })
                    }
                })
              },
              fail: function (res, reject) {
                console.log('get word fail：', res.data);
                wx.hideLoading()
              },
            })
          })

          Promise.all(promiseArr).then(res => {
            let that = this
            wx.cloud.database().collection('anmimg').add({
              data: {
                fileIDs: this.data.fileIDs,
              },
              success: res => {

                console.log('发布成功', res)
                
              },
              fail: err => {
                wx.hideLoading()
                wx.showToast({
                  icon: 'none',
                  title: '网络不给力....'
                })
                console.error('发布失败', err)
              }
            })
          })
          Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
            console.log("图片上传完成后再执行")
            this.setData({
              imgbox:[],
            })
          })
      },

      getBaiduToken: function () {
        return new Promise(resolve => {
          var APIKEY = "2cRFHlLFRIeq0lljZcKh5tnf"
          var SECKEY = "F4i4MTWK1Wqi05C0hei7MCCtbFUNoLDg"
          var tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${APIKEY}&client_secret=${SECKEY}`
          var that = this;
          wx.request({
            url: tokenUrl,
            method: 'POST',
            dataType: 'json',
            header: {
              'content-type': 'application/json; charset-UTF-8'
            },
            success: function (res) {
              console.log("[BaiduToken获取成功]", res);
              return resolve(res)
            },
            fail: function (res) {
              console.log("[BaiduToken获取失败]", res);
              return resolve(res)
            }
          })
        })
      },
    
    selectF(){ this.setData({ selectF: true}) },
    selectL(){ this.setData({ selectF: false}) },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getOpenId()
    },
    
    getOpenId() {
        wx.showLoading({
            title: '',
        });
        wx.cloud.callFunction({
            name: 'getOpenId',
        }).then((resp) => {
            this.setData({
            haveGetOpenId: true,
            openId: resp.result.openid
            });
            app.globalData.openId = resp.result.openid
            console.log(app.globalData.openId)
            wx.hideLoading();
        }).catch((e) => {
            this.setData({
            showUploadTip: true
            });
            console.log("%%%%%%%%")
            wx.hideLoading();
        });
    },
})